{isFunction} = require 'lodash'
path = require 'path'
util = require('util')
{basename} = require 'path'
klawSync = require('klaw-sync')

ROOT = "../../url/"

module.exports = (app)->
    _require = module.exports._require
    dirname = path.resolve(__dirname, ROOT)
    dirname_len = dirname.length+1
    # dir_li = []

    route = new require('./router')()
    for item in klawSync(
        dirname
        filter:(item)->
            path = item.path
            path.indexOf("/.") < 0 and path.indexOf("/_") < 0
    )
        path = item.path.slice(dirname_len)
        # if not path
        #     continue
        # if item.stats.isDirectory()
        #     dir_li.push path
        # else
        if path.endsWith('.coffee')
        # if not basename(path).startsWith("_")
            m = _require(path)
            if isFunction(m)
                m = m(app)
            if m
                prefix = path.slice(0,-7)
                if prefix.endsWith("/index")
                    prefix = prefix.slice(0, -6)
                route.use("/#{prefix}/", m.routes(), m.allowedMethods())


    route.get(
        '*'
        (ctx, next) =>
            ctx.response.status = 404
            ctx.body = 404
    )

    app.use(route.routes()).use(route.allowedMethods())

module.exports._require = (path)->
    try
        return require(ROOT+path)
    catch err
        console.trace(err)
        console.log err.toString()
        console.log "加载出错 #{path} \n"



